<?php

namespace app\service;

use app\model\Catalog as CatalogModel;
use app\model\Post as PostModel;
use support\Tree;
use support\ErrorCode;

class Catalog
{
    /**
     * 创建目录
     * @param $data
     * @return CatalogModel|\think\Model
     */
    public function create($data)
    {
        if (empty($data["parent_id"])) {
            $data["parent_id"] = 0;
        }

        if (!isset($data['number'])) {
            $data['number'] = CatalogModel::where(["parent_id" => $data["parent_id"]])->max("number") + 1;
        }


        if ($data["parent_id"] === 0) {
            $data['level'] = 1;
        } else {
            $data['level'] = CatalogModel::where("parent_id", $data["parent_id"])->value('level') + 1;
        }

        try {
            return CatalogModel::create($data);
        } catch (\Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::CREATE_CATALOG_FAILURE);
        }
    }

    /**
     * 更新目录
     * @param $data
     * @return CatalogModel
     */
    public function update($data)
    {

        try {
            if (isset($data["parent_id"])) {
                if ($data["parent_id"] === 0) {
                    $data['level'] = 1;
                } else {
                    $data['level'] = CatalogModel::where("parent_id", $data["parent_id"])->value('level') + 1;
                }

                if (!isset($data['number'])) {
                    $data['number'] = CatalogModel::where(["parent_id" => $data["parent_id"]])->max("number") + 1;
                }
            }
            return CatalogModel::update($data, ['id' => $data['id']]);
        } catch (\Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::UPDATE_CATALOG_FAILURE);
        }
    }

    /**
     * @param $data
     * @return bool
     * @throws \exception
     */
    public function delete($data)
    {
        $catalog = new CatalogModel();
        $catalogArray = $catalog->select()->toArray();
        $deleteId = [];
        $t = new Tree("id", "parent_id", "resource");
        $t->load($catalogArray);
        $catalogSub = $t->DeepTree($data['id']);
        $deleteId[] = $data['id'];
        if (!empty($catalogSub)) {
            $t->traverseTree($catalogSub, function ($item) use (&$deleteId) {
                $deleteId[] = $item["id"];
            });
        }

        $catalog->startTrans();
        try {
            //相关子目录删除
            $isCatalogDel = CatalogModel::where('id', 'in', $deleteId)->delete();
            //相关子目录及其子目录文章删除
            PostModel::where('catalog_id', 'in', $deleteId)->delete();
            $catalog->commit();
            return $isCatalogDel;
        } catch (\Exception $e) {
            $catalog->rollback();
            throw_strack_exception($e->getMessage(), ErrorCode::DELETE_CATALOG_FAILURE);
        }
    }

    /**
     * 查询出所有的目录
     * @param $filter
     * @return mixed
     * @throws \exception
     */
    public function select($filter)
    {
        try {
            $catalogList = CatalogModel::where(['item_id' => $filter["item_id"]])->order('number')->select()->toArray();

            $t = new Tree("id", "parent_id", "catalog");
            $t->load($catalogList);
            $data = $t->DeepTree();

            return $data;
        } catch (\Exception $e) {
            throw_strack_exception($e->getMessage(), ErrorCode::SELECT_CATALOG_FAILURE);
        }
    }

    /**
     * 查询目录
     * @param $param
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function findByName($param)
    {
        $query = CatalogModel::where("item_id", $param['filter']['item_id'])
            ->where("name", $param['filter']['name']);
        if (isset($param['filter']['parent_id']) && (int)$param['filter']['parent_id'] > 0) {
            $query = $query->where("parent_id", $param['filter']['parent_id']);

        }
        return $query->find();
    }
}
